home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11961 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  81 lines

  1. Path: news.rain.org!usenet
  2. From: "Guus Leeuw jr." <guusl@eiffel.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: scanf/gets interaction ?
  5. Date: Wed, 27 Mar 1996 15:38:02 -0800
  6. Organization: Interactive Software Engineering Inc. http://www.eiffel.com/
  7. Message-ID: <3159D15A.C2B4FA1@eiffel.com>
  8. References: <4j6joa$6ve@muller.loria.fr> <4jb7o2$5n1@rzsun02.rrz.uni-hamburg.de>
  9. NNTP-Posting-Host: @outback.eiffel.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; Linux 1.2.8 i586)
  14.  
  15. Christian Duehl wrote:
  16. > Denis B. Roegel (roegel@loria.fr) wrote:
  17. > : I have the following program:
  18. > :
  19. > : #include <stdio.h>
  20. > :
  21. > : main(){
  22. > : int n;
  23. > : char num[10];
  24. > : char*r;
  25. > : fflush(stdin);
  26. > : printf("n: ");scanf("%i",&n);
  27. > : printf("Numero ? ");r = gets(num);
  28. > : printf("Bien recu!\n");
  29. > : }
  30. > :
  31. > : which I compile with gcc on SunOS. The program asks for a first number n which
  32. > : I enter. But I never get a chance of entering a second one. Why is this so ?
  33. > :
  34. > Perhaps there is a loop missing :-)
  35.  
  36. Nope that is not the point.
  37.  
  38. > (In K&R I read that fflush with an input stream has a not defined effect...)
  39. > I think you could want your program so:
  40. > #include <stdio.h>
  41. > int main(void)
  42. > {
  43. >   int n;
  44. >   char num[10];  /* What happens if the input is longer than 9 chars???!!! */
  45. >   char *r;
  46. >   /* fflush(stdin); */    /* undefined effect ... (K&R) */
  47. >   printf("n: ");
  48. >   scanf("%i",&n);
  49.  
  50. The next line of code makes all the difference.
  51.  
  52. >   r = gets(num);
  53.  
  54. >   while (n>0) {
  55. >     printf("Numero ? ");
  56. >     r = gets(num);
  57. >     printf("Bien recu!\n");
  58. >     n--;
  59. >   }
  60. >   return 0;
  61. > } /* main */
  62.  
  63. What happened in the original function is that scanf reads only the digits from stdin. It
  64. lets the newline (caused by the enter) in the input buffer. The gets(num) call reads that
  65. character from stdin and stdin is clear again. Now the user is able to type new characters.
  66.  
  67. The moral of the story is: When using scanf to read numbers from stdin always remove the
  68. newline characters from stdin. `scanf' doesn't do that because that character is not a digit
  69. and thus scanf puts it back.
  70.  
  71. Hope this explains,
  72.     Guus
  73.